//
//  LoginViewController.m
//  翼安保
//
//  Created by duzhi on 2024/4/15.
//

#import "LoginViewController.h"
#import "regular.h"
#import "NSTimer+ZJSRetain.h"
#import "LoginApi.h"
#import "RegisterViewController.h"
#import "PulishFilter.h"
#import "Reachability.h"

@interface LoginViewController ()
@property (strong, nonatomic) UIImageView   *backImageView;
@property (nonatomic, strong) UIImageView   *phoneIcon;
@property (nonatomic, strong) UIImageView   *codeIcon;
@property (nonatomic, strong) UITextField   *phoneTextField;
@property (nonatomic, strong) UITextField   *codeTextfiled;
@property (nonatomic, strong) UIButton      *codeSendButton;
@property (nonatomic, strong) UIButton      *loginButton;
@property (nonatomic, strong) UIButton      *registerButton;

@property (nonatomic, strong) NSString      *phone;
@property (nonatomic, strong) NSString      *code;
@property (nonatomic, strong) NSTimer       *timer;
@property (nonatomic, assign) int times;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromRGB(0xF9F9F9);
    self.times = 60;
    [self creatUI];
    // 在你的类中创建一个Reachability对象
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    reachability.reachableBlock = ^(Reachability *reachability) {
        NSLog(@"网络已连接");
    };
    // 启动监控
    [reachability startNotifier];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)dealloc {
    [self.timer invalidate];
    NSLog(@"验证码填写界面正常释放");
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)creatUI {
    self.backImageView = [UIImageView new];
    self.backImageView.image = [UIImage imageNamed:@"bg_login"];
    [self.view addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(768/1024.f*ScreenWidth);
    }];
    
    UILabel *titleL = [UILabel new];
    titleL.text = @"安全用品全生命周期监管平台";
    titleL.font = [UIFont boldSystemFontOfSize:relativeWidth(20)];
    titleL.textColor = [UIColor whiteColor];
    [self.backImageView addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(relativeWidth(-150));
    }];
    
    UIView *inputView1 = [UIView new];
    inputView1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:inputView1];
    [inputView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.backImageView.mas_bottom).offset(relativeWidth(20));
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(relativeWidth(60));
    }];
    
    self.phoneIcon = [UIImageView new];
    self.phoneIcon.image = [UIImage imageNamed:@"login_shouji"];
    [inputView1 addSubview:self.phoneIcon];
    [self.phoneIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(10));
        make.centerY.mas_equalTo(0);
        make.width.height.mas_equalTo(26);
    }];
    
    self.phoneTextField = [UITextField new];
    self.phoneTextField.placeholder  = @"请输入手机号";
    self.phoneTextField.font         = [UIFont systemFontOfSize:relativeWidth(14)];
    self.phoneTextField.tintColor    = [UIColor blackColor];
    self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.phoneTextField addTarget:self action:@selector(phoneTextChange:) forControlEvents:UIControlEventEditingChanged];
    [inputView1 addSubview:self.phoneTextField];
    [self.phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.phoneIcon.mas_right).offset(relativeWidth(15));
        make.right.top.bottom.mas_equalTo(0);
    }];
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(inputView1.mas_bottom);
        make.height.mas_equalTo(0.5);
    }];
    
    UIView *inputView2 = [UIView new];
    inputView2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:inputView2];
    [inputView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(lineView.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(relativeWidth(60));
    }];
    
    self.codeIcon = [UIImageView new];
    self.codeIcon.image = [UIImage imageNamed:@"login_code"];
    [inputView2 addSubview:self.codeIcon];
    [self.codeIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(10));
        make.centerY.mas_equalTo(0);
        make.width.height.mas_equalTo(26);
    }];
    
    self.codeTextfiled = [UITextField new];
    self.codeTextfiled.placeholder  = @"请输入验证码";
    self.codeTextfiled.font         = [UIFont systemFontOfSize:relativeWidth(14)];
    self.codeTextfiled.tintColor    = [UIColor blackColor];
    self.codeTextfiled.keyboardType = UIKeyboardTypeNumberPad;
    [self.codeTextfiled addTarget:self action:@selector(codeTextChange:) forControlEvents:UIControlEventEditingChanged];
    [inputView2 addSubview:self.codeTextfiled];
    [self.codeTextfiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.phoneIcon.mas_right).offset(relativeWidth(15));
        make.right.top.bottom.mas_equalTo(0);
    }];
    
    if ([PulishFilter isComedMyDay]) {
        self.codeSendButton = [UIButton new];
        [self.codeSendButton setTitle:@"   发送验证码   " forState:0];
        [self.codeSendButton setTitleColor:UIColorFromRGB(0x1196db)  forState:0];
        self.codeSendButton.titleLabel.font = [UIFont systemFontOfSize:relativeWidth(14)];
        [self.codeSendButton addTarget:self action:@selector(sendCode:) forControlEvents:UIControlEventTouchUpInside];
        self.codeSendButton.layer.cornerRadius = relativeWidth(15);
        self.codeSendButton.layer.borderColor  = UIColorFromRGB(0x1196db).CGColor;
        self.codeSendButton.layer.borderWidth  = relativeWidth(1.5);
        self.codeSendButton.layer.masksToBounds = YES;
        [inputView2 addSubview:self.codeSendButton];
        [self.codeSendButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(relativeWidth(-10));
            make.height.mas_equalTo(relativeWidth(30));
            make.centerY.mas_equalTo(0);
        }];
    }else{
        self.codeTextfiled.placeholder  = @"请输入密码";
    }

    
    self.loginButton = [UIButton new];
    self.loginButton.backgroundColor = [UIColor grayColor];
    [self.loginButton setTitle:@"登录" forState:0];
    self.loginButton.layer.cornerRadius = relativeWidth(22);
    [self.loginButton setTitleColor:[UIColor whiteColor]  forState:0];
    [self.loginButton addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginButton];
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(relativeWidth(relativeWidth(-40)));
        make.height.mas_equalTo(relativeWidth(44));
        make.left.mas_equalTo(relativeWidth(40));
        make.top.mas_equalTo(inputView2.mas_bottom).offset(relativeWidth(60));
    }];
    
    self.registerButton = [UIButton new];
    self.registerButton.titleLabel.font = [UIFont systemFontOfSize:relativeWidth(14)];
    [self.registerButton setTitle:@"没有账号？注册" forState:0];
    [self.registerButton setTitleColor:UIColorFromRGB(0x1196db) forState:0];
    [self.registerButton addTarget:self action:@selector(registerClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.registerButton];
    [self.registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.height.mas_equalTo(relativeWidth(44));
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(0);
    }];
}

- (void)phoneTextChange:(UITextField *)textFiled {
    self.phone = textFiled.text;
    [self upDataLoginButton];
}

- (void)codeTextChange:(UITextField *)textFiled {
    self.code = textFiled.text;
    [self upDataLoginButton];
}

- (void)upDataLoginButton {
    if (![regular checkPhoneNumFormat:self.phone]) {
        self.loginButton.backgroundColor = [UIColor grayColor];
        return;
    }
    if (allTrim(self.code).length != 6) {
        self.loginButton.backgroundColor = [UIColor grayColor];
        return;
    }
    self.loginButton.backgroundColor = UIColorFromRGB(0x1196db);
}


- (void)login:(UIButton *)button {
    if (![regular checkPhoneNumFormat:self.phone]) {
        [MBProgressHUD showTextHUD:@"手机号码不合法" superView:self.view];
        return;
    }
    if (allTrim(self.code).length == 0) {
        if ([PulishFilter isComedMyDay]) {
            [MBProgressHUD showTextHUD:@"请输入验证码" superView:self.view];
        }else{
            [MBProgressHUD showTextHUD:@"请输入密码" superView:self.view];
        }
        return;
    }
    [self loginApi];
}

- (void)sendCode:(UIButton *)button {
    if (![regular checkPhoneNumFormat:self.phone]) {
        [MBProgressHUD showTextHUD:@"手机号码不合法" superView:self.view];
        return;
    }
    [self sendCodeApi];
}

- (void)registerClick {
    RegisterViewController *vc = [RegisterViewController new];
    [self.navigationController pushViewController:vc animated:NO];
}

- (void)setUpTimer {
    Weak(wself, self);
    if (@available(iOS 10.0, *)) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
            [wself timeGo:timer];
        }];
    } else {
        self.timer = [NSTimer zjs_scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer *timer) {
            [wself timeGo:timer];
        }];
    }
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timeGo:(NSTimer *)timer {
    NSLog(@"定时器run%d",self.times);
    if (self.times <= 1) {
        [timer invalidate];
        timer = nil;
        self.times = 60;
        [self.codeSendButton  setTitle:@"   发送验证码   " forState:0];
        self.codeSendButton.userInteractionEnabled = YES;
    }else {
        self.times -= 1;
        [self.codeSendButton  setTitle:[NSString stringWithFormat:@"    再次发送%d s   ",self.times] forState:0];
        self.codeSendButton.userInteractionEnabled = NO;
    }
}

#pragma mark api
- (void)sendCodeApi {
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"phone"] = self.phone;
    [[AFNNetWorkManager shareAFNNetWorkManager] Get:sendCodeUrl parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
        if (result.code == 200) {
            [self setUpTimer];
            [MBProgressHUD showTextHUD:@"验证码发送成功"];
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

- (void)loginApi {
    id isDelete = [[NSUserDefaults standardUserDefaults] objectForKey:@"isDelete"];
    if (![PulishFilter isComedMyDay]&&isDelete) {
        [MBProgressHUD showTextHUD:@"账号已注销"];
        return;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"phone"] = self.phone;
    NSString *url = loginUrl;
    if ([PulishFilter isComedMyDay]) {
        dic[@"smsCode"] = self.code;
    }else {
        url = @"/login/loginByPW";
        dic[@"password"] = self.code;
    }
    /*
     登录测试账号：
     13921422950
     187958
     */
    [[AFNNetWorkManager shareAFNNetWorkManager] postJson:url parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
        if (result.code == 200) {
            [[NSUserDefaults standardUserDefaults] setObject:result.data forKey:KUserInfo];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_LoginSuccess object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_foodExpairChange object:nil];
            [MBProgressHUD showTextHUD:@"登录成功"];
            [self.navigationController popViewControllerAnimated:NO];
            [self updatePlaceInfoTip];
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

- (void)updatePlaceInfoTip {
    [[AFNNetWorkManager shareAFNNetWorkManager] Get:queryRegisterInfo parameters:nil success:^(NSURLSessionDataTask *task, Result *result) {
        if (result.code == 200) {
            NSLog(@"拿到的信息：%@==%@",[result.data class],result.data);
            if ([result.data isKindOfClass:[NSDictionary class]]) {
                NSDictionary *info = result.data;
                NSString *fProvinceCode = nil;
                if ([info.allKeys containsObject:@"fProvinceCode"]) {
                    fProvinceCode = info[@"fProvinceCode"];
                }
                NSString *fCityCode = nil;
                if ([info.allKeys containsObject:@"fCityCode"]) {
                    fCityCode = info[@"fCityCode"];
                }
                NSString *fAreaCode = nil;
                if ([info.allKeys containsObject:@"fAreaCode"]) {
                    fAreaCode = info[@"fAreaCode"];
                }
                if (!fProvinceCode||!fCityCode||!fAreaCode) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [MBProgressHUD showTextHUD:@"请在个人信息中，更新区域信息"];
                    });
                    
                }
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

@end
